package mogodb;
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class MongodbJDBC {
	public static void main(String[] args) {
		try {
			
			//连接到mongodb服务
			MongoClient mongoClient=new MongoClient(); 
			//连接到数据库
			MongoDatabase mongoDatabase=mongoClient.getDatabase("jxy");
			System.out.println("mongodb is success to connect.");
			
			
			//选择集合
			 MongoCollection<Document> collection = mongoDatabase.getCollection("col");
			 
			/*
			 * 插入文档
			 */
			Document document=new Document("title","mongodb").
					append("descrip", "join");
			List<Document> documents=new ArrayList<>();
			documents.add(document);
			collection.insertMany(documents);
			System.out.println("文档插入成功");
			
			/*
			 * 检索所有文档
			 */
			FindIterable<Document> findIterable=collection.find();
			MongoCursor<Document> mongoCursor=findIterable.iterator();
			while(mongoCursor.hasNext()) {
				System.out.println(mongoCursor.next());
			}
			
			/*
			 * 更新文档
			 */
			collection.updateMany(Filters.eq("title", "Mongodb"), new Document("$set",new Document("title","MongoDB")));
			
			/*
			 *删除第一个文档 
			 */
			 //删除符合条件的第一个文档  
	         //collection.deleteOne(Filters.eq("descrip", "join"));  
	         //删除所有符合条件的文档  
	         collection.deleteMany (Filters.eq("descrip", "join"));  
	         
	        
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
